#include "stdafx.h"

#include "PC2DataStore.h"

#include "BankTransactionStoreExecutor.h"


namespace PC2
{

TimeIDGenerator::TimeIDGenerator()
: m_LastTime(0)
, m_Count(0)
{

}

std::string TimeIDGenerator::GetNextID()
{
	time_t lTime = time(NULL);
	tm lTm;

#ifdef WINDOWS
	localtime_s(&lTm, &lTime);
#else
	localtime_r(&lTime, &lTm);
#endif

	if(m_LastTime == lTime)
	{
		m_Count ++;
	}
	else
	{
		m_LastTime = lTime;
		m_Count = 0;
	}

	char lBuffer[64];
	sprintf(lBuffer, "%04d%02d%02d%02d%02d%02d:%u"
	, lTm.tm_year + 1900
	, lTm.tm_mon + 1
	, lTm.tm_mday
	, lTm.tm_hour
	, lTm.tm_min
	, lTm.tm_sec
	, m_Count);

	return std::string(lBuffer);

}

BankTransactionStoreExecutor::BankTransactionStoreExecutor( PC2DataStore* apStore )
	: m_pStore(apStore)
	, m_IDGenerator()
{

}

BankTransactionStoreExecutor::~BankTransactionStoreExecutor()
{

}

void BankTransactionStoreExecutor::DumpAllTransaction( std::vector<std::pair<std::string, BankTransaction> >* apVec )
{
	leveldb::Iterator* lpIt = m_pStore->CreateIterator();

	for (lpIt->SeekToFirst(); lpIt->Valid(); lpIt->Next())
	{
		BankTransaction* lpTrans;
		std::string lKeyString = lpIt->key().ToString();
		if(lpIt->key().starts_with("_BT_"))
		{
			lpTrans = (BankTransaction*)lpIt->value().data();
			apVec->push_back(std::make_pair(lKeyString, *lpTrans));
		}
	}

	delete lpIt;
}

bool BankTransactionStoreExecutor::Prepare( uint32_t aTransId, char const* apData, uint32_t aSize, leveldb::WriteBatch* apBatch )
{
	LOG("prepare OK\n");
	return true;
}

void BankTransactionStoreExecutor::Commit( uint32_t aTransId, char const* apData, uint32_t aSize, leveldb::WriteBatch* apBatch )
{
	std::string lID = GetNextID();

	apBatch->Put(lID, leveldb::Slice(apData, aSize));

	BankTransaction* apTrans = (BankTransaction*)apData;

	LOG("commit OK\n");
	LOG("name %s from %s to %s value %u\n", apTrans->m_Name,apTrans->m_BankFrom,apTrans->m_BankTo,apTrans->m_Value);
}

void BankTransactionStoreExecutor::Abort( uint32_t aTransId, char const* apData, uint32_t aSize, leveldb::WriteBatch* apBatch )
{
	LOG("abort OK\n");
	return;
}

std::string BankTransactionStoreExecutor::GetNextID()
{
	std::string lRet("_BT_");
	lRet.append(m_IDGenerator.GetNextID());
	return lRet;
}


}
